package com.ccf.business.etl.flow.mq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.component.api.constants.FlowConstants;
import com.ccf.business.etl.model.FlowLog;
import com.ccf.business.etl.service.IFlowLogService;
import com.ccf.business.etl.websocket.FlowTestLogHandler;
import com.common.log.LogFlowInfo;
import com.framework.rocketmq.consumer.Consumer;
import com.framework.rocketmq.consumer.MQConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.DelayQueue;
import java.util.stream.Collectors;

/**
 * 描述：
 * 流程日志接收
 * @author xianggj
 * @Date 2021/12/7 18:22
 **/
@Slf4j
@Component
public class FlowLogConsumer extends Consumer {

    @Autowired
    private IFlowLogService flowLogService;

    @Autowired
    private FlowTestLogHandler flowTestLogHandler;

    /**
     * 延时队列
     */
    private static final DelayQueue<FlowLog> queue = new DelayQueue<>();

    /**
     * 延时时间
     * 每0.5秒取一次数据
     */
    private static final long DELAY_TIME = 500;

    @Override
    protected void consume(MessageExt msg, ConsumeConcurrentlyContext context) throws Exception {
        String content = new String(msg.getBody(), StandardCharsets.UTF_8);
        log.info("msg:" + content);
        try {
            LogFlowInfo logFlowInfo = JSON.parseObject(content, LogFlowInfo.class);
            String flowId = logFlowInfo.getFlowId();
            FlowLog flowLog = new FlowLog(logFlowInfo, DELAY_TIME);
            queue.offer(flowLog);
            List<FlowLog> list = new ArrayList<>();
            saveAndSend(flowId, list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("无效消息！"+ content);
            return;
        }
    }

    /**
     * 保存和发送
     * @param flowId
     * @param list
     * @throws Exception
     */
    private synchronized void saveAndSend(String flowId, List<FlowLog> list) throws Exception {
        if (queue.size() ==  0) {
            return;
        }
        FlowLog take = queue.take();
        list.add(take);
        CollUtil.addAll(list, queue.toArray(new FlowLog[0]));
        queue.clear();
        flowLogService.saveBatch(list);
        Set<String> flowIds = list.stream().map(e -> e.getFlowId())
                .filter(e-> StrUtil.startWith(flowId, FlowConstants.TEST_FLOW))
                .collect(Collectors.toSet());
        for (String fid : flowIds) {
            flowTestLogHandler.sendMessage(fid);
        }
    }

    @Override
    protected MQConfig getMQConfig() {
        return new MQConfig(LogFlowInfo.TOPIC);
    }

    @Override
    protected String getGroupName() {
        return "flowLogGroupName";
    }
}
